package com.inspectionwork.web.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.inspectionwork.common.base.BaseService;
import com.inspectionwork.common.utils.Dict;
import com.inspectionwork.model.*;
import com.inspectionwork.support.model.RespEntity;
import com.inspectionwork.support.mybatisplus.QueryWrapper;
import com.inspectionwork.support.utils.requestutil.HttpRequestUtil;
import com.inspectionwork.web.mapper.*;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Service
@Slf4j
public class InspectionworkService extends BaseService {

	private static final Logger logger = LoggerFactory.getLogger(InspectionworkService.class);

	@Resource
	private InspectionWorkMapper inspectionWorkMapper;
	@Resource
	private RelevantFilesMapper relevantFilesMapper;
	@Resource
	private RelevantUnitsMapper relevantUnitsMapper;
	@Resource
	private UseDictMapper useDictMapper;
	@Resource
	private BusinessMapper businessMapper;


	/**
	 * 检查工作下发列表查询
	 * @param
	 * @return
	 */
	public RespEntity listInspectionworkListPage(JSONObject jsonParam){
		jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
		Page<DeviceBusiness> page = new Page<>(jsonParam.getInt("page"), jsonParam.getInt("limit"));
		//调用token验证接口
		com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam,"systemsetup","config","getDecodeToken","systemsetup");
		if(StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
		if(StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
		String homeId = token.getString("home_id");
		String userType = token.getString("user_type");
		IPage<InspectionWork> pageList = null;
		jsonParam.put("homeId",homeId);
		if(userType.equals("1")){//为机构用户
			pageList = inspectionWorkMapper.inspectionworkListPageForOrg(page, jsonParam);
		}else if(userType.equals("2")){//为单位用户
			pageList = inspectionWorkMapper.inspectionworkListPageForBu(page, jsonParam);
		}
		Map<String,Object> data = new HashMap<>();
		data.put("totalSize", pageList.getTotal());//总条数
		data.put("pageSize", pageList.getSize());//每页展示多少条
		data.put("currentPage", pageList.getCurrent());//当前页
		data.put("Items", pageList.getRecords());//数据
		data.put("pages", pageList.getPages());//总页数
		data.put("currentSize", pageList.getRecords().size());//当前页多少条
		return RespEntity.success(data);
	}

	/**
	 * 检查落实任务列表：单位用
	 * @param
	 * @return
	 */
	public RespEntity workableList(JSONObject jsonParam){
		jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
		//调用token验证接口
		com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam,"systemsetup","config","getDecodeToken","systemsetup");
		if(StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
		if(StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
		String homeId = token.getString("home_id");
		String userType = token.getString("user_type");
		LinkedHashMap<String,Object> map = new LinkedHashMap<>();//包装最终的数据
		jsonParam.put("homeId",homeId);
		//查询未落实列表
		jsonParam.put("isworkable",false);
		List<Map<String,Object>> noWorkableList = inspectionWorkMapper.workableList(jsonParam);
		map.put("未落实检查任务",noWorkableList);
		//查询已经落实列表
		jsonParam.put("isworkable",true);
		List<Map<String,Object>> yesWorkableList = inspectionWorkMapper.workableList(jsonParam);
		map.put("已落实检查任务",yesWorkableList);
		return RespEntity.success(map);
	}

	/**
	 * 检查工作下发列表新增
	 * @param
	 * @return
	 */
	public RespEntity addInspectionwork(JSONObject jsonParam) {
		//处理支持form-data和json两种方式
		jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
		//调用token验证接口
		com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam,"systemsetup","config","getDecodeToken","systemsetup");
		if(StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
		if(StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
		String homeId = token.getString("home_id");
		String userType = token.getString("user_type");
		String userId = token.getString("user_id");
		if (!jsonParam.getBool("ishaveReceivingUnit")) {
			return RespEntity.fail("没有接收单位");
		}
		//保存检查工作下发
		String uuid = UUID.randomUUID().toString();
		InspectionWork inspectionWork = new InspectionWork();
		inspectionWork.setId(uuid);
		inspectionWork.setTitle(jsonParam.getStr("title"));
		inspectionWork.setType(jsonParam.getStr("type"));
		inspectionWork.setDes(jsonParam.getStr("des"));
		inspectionWork.setStarttime(jsonParam.getDate("starttime"));
		inspectionWork.setLowerhairtime(new Date());
		inspectionWork.setOrgId(homeId);
		inspectionWork.setCreatePersonId(userId);
		inspectionWork.setIshaveFile(jsonParam.getBool("ishaveFile"));
		inspectionWork.setIshaveReceivingUnit(jsonParam.getBool("ishaveReceivingUnit"));
		inspectionWork.setOrgName(jsonParam.getStr("homeName"));
		if(jsonParam.getBool("ishaveReceivingUnit")){//如果有接收单位
			if(jsonParam.getBool("allflag")){//如果选择了下辖所有单位
				inspectionWork.setAllflag(jsonParam.getBool("allflag"));
				inspectionWork.setBottomArea(jsonParam.getStr("bottomArea"));
				//rest请求:获取所有上级行政区划接口
				JSONObject jsonParamN = new JSONObject();
				jsonParamN.put("bottomArea",jsonParam.getStr("bottomArea"));
				com.alibaba.fastjson.JSONObject allAreas = makeDataForToken(jsonParamN,"businessJava","config","getAllArea","alarmInfo");
				if(StrUtil.isNotBlank(allAreas.getString("methodErrorFlag"))) return RespEntity.fail(allAreas.getString("msg"));
				String allArea = allAreas.getString("allArea");
				inspectionWork.setArea(allArea);
				//根据机构id和区划，获取所有单位的信息，保存到接收单位表中
				jsonParamN = new JSONObject();
				jsonParamN.put("orgId",homeId);
				jsonParamN.put("area",allArea.startsWith(",")?allArea.substring(1,allArea.length()):allArea);
				JSON businessListJson = makeDataForJSONForToken(jsonParamN,"businessJava","config","businessList","alarmInfo");
				if(businessListJson instanceof com.alibaba.fastjson.JSONObject){
					com.alibaba.fastjson.JSONObject checkaddrRecordListJsonN = (com.alibaba.fastjson.JSONObject)businessListJson;
					if(StrUtil.isNotBlank(checkaddrRecordListJsonN.getString("methodCodeFlag"))){
						return RespEntity.expire();
					}
					return RespEntity.fail(((com.alibaba.fastjson.JSONObject) businessListJson).getString("msg"));
				}else{
					JSONArray businessList = (JSONArray)businessListJson;
					List<RelevantUnits> buList = new ArrayList<>();
					for(Object ob : businessList){
						com.alibaba.fastjson.JSONObject business = (com.alibaba.fastjson.JSONObject)ob;
						RelevantUnits relevantUnits = new RelevantUnits();
						relevantUnits.setIsworkable(false);
						relevantUnits.setReceivingUnitId(business.getString("id"));
						relevantUnits.setReceivingUnitName(business.getString("name"));
						relevantUnits.setRelevantId(uuid);
						relevantUnits.setWorkabletime(null);
						buList.add(relevantUnits);
					}
					if(buList.isEmpty()){
						return RespEntity.fail("此区域没有接收单位");
					}
					//批量保存接收单位
					inspectionWorkMapper.insertAllUnits(buList);
				}
			}else{//如果不是选择下辖所有单位
				inspectionWork.setAllflag(jsonParam.getBool("allflag"));
				//根据组装好的id数组，获取所有单位的信息，保存到接收单位表中
				String units = jsonParam.getStr("units");
				String[] unitList = units.split(",");
				List<Business> businessList = businessMapper.getBusinessList(unitList);
				JSONObject jsonParamN = new JSONObject();
				jsonParamN.put("ids",unitList);
				List<RelevantUnits> buList = new ArrayList<>();
				for(Business b : businessList){
					RelevantUnits relevantUnits = new RelevantUnits();
					relevantUnits.setIsworkable(false);
					relevantUnits.setReceivingUnitId(b.getId());
					relevantUnits.setReceivingUnitName(b.getName());
					relevantUnits.setRelevantId(uuid);
					relevantUnits.setWorkabletime(null);
					buList.add(relevantUnits);
				}
				if(buList.isEmpty()){
					return RespEntity.fail("没有接收单位");
				}
				//批量保存接收单位
				inspectionWorkMapper.insertAllUnits(buList);
			}
		}
		if(jsonParam.getBool("ishaveFile")){//如果有附件
			RelevantFiles relevantFiles = new RelevantFiles();
			JSONObject file = jsonParam.getJSONObject("filePath");
			relevantFiles.setFileName(file.getStr("fileName"));
			relevantFiles.setFilePath(file.getStr("filePath"));
			relevantFiles.setRelevantId(uuid);
			relevantFilesMapper.insert(relevantFiles);
		}
		//新增
		inspectionWorkMapper.insert(inspectionWork);
		return RespEntity.success();
	}

	/**
	 * 检查工作下发详情
	 * @param
	 * @return
	 */
	public RespEntity getById(JSONObject jsonParam) {
		jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
		//调用token验证接口
		com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam,"systemsetup","config","getDecodeToken","systemsetup");
		if(StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
		if(StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
		String homeId = token.getString("home_id");
		String userType = token.getString("user_type");
		//查询检查工作下发详情
		InspectionWork InspectionWork = inspectionWorkMapper.getInspectionWorkById(jsonParam);
		if(InspectionWork == null){
			return RespEntity.fail("传入的id错误");
		}
		//如果ishaveFile=1,获取图片名字和路径
		if(InspectionWork.getIshaveFile()){
			Map<String,Object> fileMap = inspectionWorkMapper.getFileField(jsonParam);
			InspectionWork.put("fileName",fileMap.get("fileName")==null?"":fileMap.get("fileName"));
			InspectionWork.put("filePath",fileMap.get("filePath")==null?"":fileMap.get("filePath"));
		}
		//查询下发单位的数量
		int distributionCount = inspectionWorkMapper.getDistributionCount(jsonParam);
		InspectionWork.put("distributionCount",distributionCount);
		//查询落实单位的数量
		int workableCount = inspectionWorkMapper.getWorkableCount(jsonParam);
		InspectionWork.put("workableCount",workableCount);
		return RespEntity.success(InspectionWork);
	}

	/**
	 * 单位的落实情况列表
	 * @param
	 * @return
	 */
	public RespEntity workableBusinessListPage(JSONObject jsonParam) {
		jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
		//调用token验证接口
		com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam,"systemsetup","config","getDecodeToken","systemsetup");
		if(StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
		if(StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
		String homeId = token.getString("home_id");
		String userType = token.getString("user_type");
		//查询接收单位列表
		List<RelevantUnits> relevantUnitsList = inspectionWorkMapper.getRelevantUnitsList(jsonParam);
		//组装单位id和是否落实的对应关系
		Dict map = new Dict();
		List<String> ids = new ArrayList<>();
		for(RelevantUnits relevantUnits : relevantUnitsList){
			map.put(relevantUnits.getStr("id"),relevantUnits.getBool("isworkable"));
			ids.add(relevantUnits.getStr("id"));
		}
		//rest获取单位列表：根据相关参数
		JSONObject jsonParamN = new JSONObject();
		//jsonParamN.put("ids",ids);
		jsonParamN.put("name",jsonParam.getStr("name"));
		jsonParamN.put("fireRating",jsonParam.getStr("fireRating"));
		jsonParamN.put("page",jsonParam.getInt("page"));
		jsonParamN.put("limit",jsonParam.getInt("limit"));
		com.alibaba.fastjson.JSONObject businessDetail = makeDataForToken(jsonParamN,"businessJava","config","businessListPage","alarmInfo");
		if(StrUtil.isNotBlank(businessDetail.getString("methodErrorFlag"))) return RespEntity.fail(businessDetail.getString("msg"));
		JSONArray Items = businessDetail.getJSONArray("Items");
		for(Object bu : Items){//赋值上落实和未落实的字段
			com.alibaba.fastjson.JSONObject buJsonObject = (com.alibaba.fastjson.JSONObject)bu;
			Boolean isworkable = map.getBool(buJsonObject.getString("id"));
			buJsonObject.put("isworkable",isworkable);
			buJsonObject.put("isworkableName",isworkable?"已落实":"未落实");
		}
		businessDetail.put("Items",Items);//赋值改装后的新的列表
		return RespEntity.success(businessDetail);
	}

	/**
	 * 单位落实
	 * @param
	 * @return
	 */
	public RespEntity workable(JSONObject jsonParam) {
		//处理支持form-data和json两种方式
		jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
		//调用token验证接口
		com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam,"systemsetup","config","getDecodeToken","systemsetup");
		if(StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
		if(StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
		String homeId = token.getString("home_id");
		String userType = token.getString("user_type");
		//根据单位id修改落实状态
		RelevantUnits relevantUnits = new RelevantUnits();
		relevantUnits.setIsworkable(true);
		relevantUnitsMapper.update(relevantUnits,new QueryWrapper<RelevantUnits>().eq("relevant_id",jsonParam.getStr("id")).eq("receiving_unit_id",homeId));
		return RespEntity.success();
	}

	/**
	 * 单位落实修改为未落实
	 * @param
	 * @return
	 */
	public RespEntity workableNo(JSONObject jsonParam) {
		//处理支持form-data和json两种方式
		jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
		//调用token验证接口
		com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam,"systemsetup","config","getDecodeToken","systemsetup");
		if(StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
		if(StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
		String homeId = token.getString("home_id");
		String userType = token.getString("user_type");
		//根据单位id修改落实状态
		RelevantUnits relevantUnits = new RelevantUnits();
		relevantUnits.setIsworkable(false);
		relevantUnitsMapper.update(relevantUnits,new QueryWrapper<RelevantUnits>().eq("relevant_id",jsonParam.getStr("id")).eq("receiving_unit_id",homeId));
		return RespEntity.success();
	}

	/**
	 * 字典组查询
	 * @param
	 * @return
	 */
	public RespEntity dictList(JSONObject jsonParam) {
		//处理支持form-data和json两种方式
		jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
		//调用token验证接口
		com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam,"systemsetup","config","getDecodeToken","systemsetup");
		if(StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
		if(StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
		List<UseDict> dictlist = useDictMapper.selectList(new QueryWrapper<UseDict>().eq("groupname",jsonParam.getStr("groupname")).orderByAsc("sortid"));
		return RespEntity.success(dictlist);
	}

	//检查工作下发删除
    public RespEntity delete(JSONObject jsonParam) {
		//处理支持form-data和json两种方式
		jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
		//调用token验证接口
		com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
		if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
		if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
		String homeId = token.getString("home_id");
		String userId = token.getString("user_id");
		String id = jsonParam.getStr("id");
		List<RelevantUnits> relevant = this.relevantUnitsMapper.selectList(new QueryWrapper<RelevantUnits>().eq("relevant_id", id));
		if (relevant.isEmpty()) return RespEntity.fail("检查工作任务不存在!");
		int count = relevantUnitsMapper.selectCount(new QueryWrapper<RelevantUnits>().eq("relevant_id",id).eq("isworkable",1));
		//1代表true 0代表false  0 未落实 1 已落实
		if (count<=0) {
			//删除inspectionWork
			this.inspectionWorkMapper.delete(new QueryWrapper<InspectionWork>().eq("id", id));
			this.relevantFilesMapper.delete(new QueryWrapper<RelevantFiles>().eq("relevant_id", id));
			this.relevantUnitsMapper.delete(new QueryWrapper<RelevantUnits>().eq("relevant_id", id));
			return RespEntity.success();
		}
		return RespEntity.fail("已有单位落实,不能删除!");
	}
}
